<template>
  <div>
    <Row style="align-items: flex-start;margin-bottom:5px;display:block">
      <Col :lg="10" :xs="22" offset="0.5">
      <vxe-toolbar :refresh="{ query: reload }" print v-if="isUpdate">
        <template #buttons>
          <vxe-button size="mini" status="primary" @click="impotEvent">导入</vxe-button>
          <vxe-button size="mini" status="primary" @click="exportFile">导出</vxe-button>
          <vxe-button size="mini" status="primary" @click="addRow">新增</vxe-button>
          <vxe-button size="mini" status="danger" @click="delRow">删除</vxe-button>
          <vxe-button size="mini" @click="saveData">保存</vxe-button>
        </template>
      </vxe-toolbar>

      <vxe-table ref="xTable" height="400" border highlight-hover-row show-overflow :edit-rules="validRules"
        class="sortable-row-demo" :data="tablePage.listPage" :print-config="{}" :export-config="{
          filename: filename(),
          columnFilterMethod: filterExport1,
          type: 'cvs'
        }" :loading="loading" :edit-config="{ trigger: 'click', mode: 'cell', enabled: isUpdate }">
        <vxe-column v-if="isUpdate" type="checkbox" width="60"></vxe-column>
        <vxe-column v-if="isUpdate" width="60">
          <template #default>
            <span class="drag-btn">
              <i class="vxe-icon--menu"></i>
            </span>
          </template>
          <template #header>
            <vxe-tooltip v-model="showHelpTip1" content="按住后可以上下拖动排序！" enterable>
              <i class="vxe-icon--question" @click="showHelpTip1 = !showHelpTip1"></i>
            </vxe-tooltip>
          </template>
        </vxe-column>
        <vxe-column field="time" title="时间(s)" :edit-render="{ name: 'input' }"></vxe-column>
        <vxe-column field="speed" title="车速(km/h)" :edit-render="{ name: 'input' }"></vxe-column>
        <vxe-column field="load" title="载荷(kg)" :edit-render="{ name: 'input' }"></vxe-column>
        <vxe-column field="gradient" title="坡度(%)" :edit-render="{ name: 'input' }"></vxe-column>
      </vxe-table>

      <vxe-pager :current-page="tablePage.currentPage" :page-size="tablePage.pageSize" :total="tablePage.totalResult"
        :layouts="[
          'PrevPage',
          'JumpNumber',
          'NextPage',
          'FullJump',
          'Sizes',
          'Total'
        ]" @page-change="handlePageChange">
      </vxe-pager>
      </Col>
      <Col :lg="12" :xs="22" offset="0.5">
      <div style="height:470px;" id="a"></div>
      </Col>
    </Row>
  </div>
</template>

<script>
import { gearboxEfficiencyApi } from "@/api/gearbox-efficiency";
import { gearboxShiftApi } from "@/api/gearbox-shift";
import { drivingCycleTbApi } from "@/api/driving-cycle-tb.js";
import XLSX, { WorkSheet } from "xlsx";
import Sortable from "sortablejs";
export default {
  name: "DrivingCycleTable",
  components: {},
  props: {
    drivingCycleId: {
      type: Number
    },
    isUpdate: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      validRules: {
        speedRatio: [
          { pattern: "^[0-9]+.?[0-9]*$", message: "请输入数字类型" }
        ],
        torqueRatio: [
          { pattern: "^[0-9]+.?[0-9]*$", message: "请输入数字类型" }
        ],
        capacity: [{ pattern: "^[0-9]+.?[0-9]*$", message: "请输入数字类型" }],
        efficiency: [{ pattern: "^[0-9]+.?[0-9]*$", message: "请输入数字类型" }]
      },
      sortable1: null,
      showHelpTip1: false,
      detail: {}, // 详情信息
      torqueConvertId: null,
      tableData: [], // 表格列表数据-- 总数据
      tablePage: {
        currentPage: 1,
        pageSize: 10,
        totalResult: 0,
        listPage: []
      },
      // 表单验证
      formValidate: {
        // 编号
        sn: [{ required: true, message: "请输入编号", trigger: "change" }],
        // 型号
        model: [{ required: true, message: "请输入型号", trigger: "change" }],

        // 循环圆直径(mm)
        diameter: [
          {
            type: "number",
            required: true,
            message: "请输入循环圆直径(mm)",
            trigger: "change"
          },
          {
            type: "number",
            min: 0,
            max: 5000,
            message: "请输入0到5000的数字",
            trigger: "change"
          }
        ],
        // 启动变矩比
        initialTorqueRatio: [
          {
            type: "number",
            required: true,
            message: "请输入启动变矩比",
            trigger: "change"
          },
          {
            type: "number",
            min: 0,
            max: 100,
            message: "请输入0到100的数字",
            trigger: "change"
          }
        ],
        pumpInertia: [
          {
            type: "number",
            min: 0,
            max: 10,
            message: "请输入0到10的数字",
            trigger: "change"
          }
        ],
        turbineInertia: [
          {
            type: "number",
            min: 0,
            max: 10,
            message: "请输入0到10的数字",
            trigger: "change"
          }
        ],
        oilDensity: [
          {
            type: "number",
            min: 0,
            max: 1000,
            message: "请输入0到1000的数字",
            trigger: "change"
          }
        ],
        weight: [
          {
            type: "number",
            min: 0,
            max: 3000,
            message: "请输入0到3000的数字",
            trigger: "change"
          }
        ],
        // 特性类型
        type: [
          { required: true, message: "请输入特性类型", trigger: "change" }
        ],
        // 图片
        image: [{ required: true, message: "请上传图片", trigger: "change" }]
      }
    };
  },
  watch: {
    /// 深度监听，可监听到对象、数组的变化  (table数据变化时，渲染echart)
    tableData: {
      handler(newVal, oldVal) {
        this.renderEchart();
      },
      deep: true // true 深度监听
    }
  },
  filters: {},
  created() {
    this.columnDrop2();
  },
  mounted() {
    // 初始化数据
    this.initData();

    this.rowDrop();
  },
  methods: {
    filename() {
      var date = new Date();
       var dateStr = new Date(+new Date() + 8 * 3600 * 1000)
        .toJSON()
        .substr(0, 19)
        .replace("T", "")
        .replaceAll("-", "")
        .replaceAll(":", "")
      return ("行驶工况曲线" + dateStr);

    },
    exportFile() {
      this.$refs.xTable.exportData({ type: "csv" });
    },
    filterExport1(data) {
      // 返回false 就是导出不显示
      if (!data.column.title) return false;
      if (data.column.type == "checkbox") return false;
      return true;
    },

    // 刷新表格
    reload() {
      const $table = this.$refs.xTable;
      // 清除所有状态
      $table.clearAll();
      // 初始化数据
      this.initData();
    },
    columnDrop2() {
      this.$nextTick(() => {
        const $table = this.$refs.xTable;
        this.sortable2 = Sortable.create(
          $table.$el.querySelector(
            ".body--wrapper>.vxe-table--header .vxe-header--row"
          ),
          {
            handle: ".vxe-header--column:not(.col--fixed)",
            onEnd: ({ item, newIndex, oldIndex }) => {
              const { fullColumn, tableColumn } = $table.getTableColumn();
              const targetThElem = item;
              const wrapperElem = targetThElem.parentNode;
              const newColumn = fullColumn[newIndex];
              if (newColumn.fixed) {
                // 错误的移动
                if (newIndex > oldIndex) {
                  wrapperElem.insertBefore(
                    targetThElem,
                    wrapperElem.children[oldIndex]
                  );
                } else {
                  wrapperElem.insertBefore(
                    wrapperElem.children[oldIndex],
                    targetThElem
                  );
                }
                return this.$XModal.message({
                  content: "固定列不允许拖动！",
                  status: "error"
                });
              }
              // 转换真实索引
              const oldColumnIndex = $table.getColumnIndex(
                tableColumn[oldIndex]
              );
              const newColumnIndex = $table.getColumnIndex(
                tableColumn[newIndex]
              );
              // 移动到目标列
              const currRow = fullColumn.splice(oldColumnIndex, 1)[0];
              fullColumn.splice(newColumnIndex, 0, currRow);
              $table.loadColumn(fullColumn);
            }
          }
        );
      });
    },

    // 行数据移动
    rowDrop() {
      this.$nextTick(() => {
        const xTable = this.$refs.xTable;
        this.sortable1 = Sortable.create(
          xTable.$el.querySelector(".body--wrapper>.vxe-table--body tbody"),
          {
            handle: ".drag-btn",
            onEnd: ({ newIndex, oldIndex }) => {
              const currRow = this.tableData.splice(oldIndex, 1)[0];
              this.tableData.splice(newIndex, 0, currRow);
            }
          }
        );
      });
    },
    // 翻页
    handlePageChange({ currentPage, pageSize }) {
      this.tablePage.currentPage = currentPage;
      this.tablePage.pageSize = pageSize;
      this.findList();
    },

    findList() {
      // 总数据
      this.tablePage.totalResult = this.tableData.length;
      this.tablePage.listPage = this.tableData.slice(
        (this.tablePage.currentPage - 1) * this.tablePage.pageSize,
        this.tablePage.currentPage * this.tablePage.pageSize
      );
    },

    // 导入
    impotEvent() {
      this.$refs.xTable
        .readFile({
          types: ["xls", "xlsx", "csv"]
        })
        .then(params => {
          const { files } = params;
          const fileReader = new FileReader();
          fileReader.onload = ev => {
            const data = ev.target.result;
            const workbook = XLSX.read(data, { type: "binary" });
            const csvData = XLSX.utils.sheet_to_csv(workbook.Sheets.Sheet1);
            const tableData = [];
            // 解析数据csvData
            csvData.split("\n").forEach((vRow, index) => {
              if (index == 0) {
                return;
              }
              if (vRow) {
                const vCols = vRow.split(",");
                const item = {};
                vCols.forEach((val, cIndex) => {
                  if (cIndex == 0) {
                    item["time"] = val;
                  } else if (cIndex == 1) {
                    item["speed"] = val;
                  } else if (cIndex == 2) {
                    item["load"] = val;
                  } else if (cIndex == 3) {
                    item["gradient"] = val;
                  }

                  item["index"] = Number(
                    Math.random()
                      .toString()
                      .substr(2, 10) + Date.now()
                  ).toString(36);
                });
                tableData.push(item);
              }
            });
            this.tableData = tableData;
            this.findList();
          };
          fileReader.readAsBinaryString(files[0]);
        });
    },
    exportExcel1() {
      const workBook = XLSX.utils.table_to_book(
        this.$refs.xTable.$el.querySelector(".body--wrapper>.vxe-table--body")
      );
      XLSX.writeFile(workBook, "行驶工况特性曲线.xlsx");
    },
    /**
     * @desc 渲染echart
     * @sicne 2021/11/13
     */
    renderEchart() {
      // 组合数据格式[x, y]
      // 车速
      const speeds = [];
      // 载荷
      const loads = [];
      // 坡度
      const gradients = [];

      // 曲线回转问题修改
      let tempTableData = [...this.tableData];
      tempTableData.sort((a, b) => a.time - b.time); // 排序

      tempTableData.forEach(item => {
        const temp = [];
        temp.push(item.time);
        temp.push(item.speed);
        speeds.push(temp);

        const tmep1 = [];
        tmep1.push(item.time);
        tmep1.push(item.load);
        loads.push(tmep1);

        const tmep2 = [];
        tmep2.push(item.time);
        tmep2.push(item.gradient);
        gradients.push(tmep2);
      });

      const line_map = { a: "车速", b: "载荷", c: "坡度" };

      const option = {
        title: {
          text: "行驶工况曲线"
        },
        tooltip: {
          trigger: "item",
          formatter: function (params) {
            let str = "";
            if (params) {
              const { seriesId } = params;
              str =
                str +
                line_map[seriesId] +
                "->[" +
                params.data[0] +
                ", " +
                params.data[1] +
                "]";
              str += "</br>";
            } else {
              return "";
            }

            return str;
          }
        },
        legend: {
          x: "right",
          data: ["车速", "载荷", "坡度"],
          textStyle: {
            fontsize: 5
          }
        },
        grid: {
          top: "20%",
          left: "24%",
          right: "4%",
          containLabel: true
        },

        xAxis: {
          type: "value",
          name: "时间(s)",
          nameLocation: "center",
          axisLine: { onZero: false },
          nameGap: 20
        },
        yAxis: [
          {
            name: "坡度(%)",
            axisLine: {
              lineStyle: {
                color: "#248EFD"
              },
              show: true
            },
            type: "value",
            position: "left",
            splitLine: {
              show: false
            }
          },
          {
            name: "载荷(kg)",
            axisLine: {
              lineStyle: {
                color: "#FD2446"
              },
              show: true
            },
            type: "value",
            position: "left",
            splitLine: {
              show: false
            },
            offset: 70
          },
          {
            name: "车速(km/h)",
            axisLine: {
              lineStyle: {
                color: "#C916F2"
              },
              show: true
            },
            type: "value",
            position: "left",
            splitLine: {
              show: false
            },
            offset: 130
          }
        ],
        series: [
          {
            id: "a",
            name: "车速",
            type: "line",
            smooth: true,
            symbolSize: 5,
            data: speeds,
            yAxisIndex: "2",
            itemStyle: {
              normal: {
                color: "#C916F2",
                lineStyle: {
                  color: "#C916F2"
                }
              }
            }
          },
          {
            id: "b",
            type: "line",
            name: "载荷",
            smooth: true,
            symbolSize: 5,
            data: loads,
            yAxisIndex: "1",
            itemStyle: {
              normal: {
                color: "#FD2446",
                lineStyle: {
                  color: "#FD2446"
                }
              }
            }
          },
          {
            id: "c",
            name: "坡度",
            type: "line",
            smooth: true,
            symbolSize: 10,
            data: gradients,
            yAxisIndex: "0",
            itemStyle: {
              normal: {
                color: "#248EFD",
                lineStyle: {
                  color: "#248EFD"
                }
              }
            }
          }
        ]
      };
      let myChart = this.echarts.init(document.getElementById("a"));
      myChart.clear();
      myChart.setOption(option);
    },

    /**
     * @desc 添加行数据
     */
    addRow() {
      const $table = this.$refs.xTable;
      const record = {
        time: null,
        speed: null,
        load: null,
        gradient: null,
        index: new Date().getTime()
      };
      this.tableData.push(record);
      this.findList();
      const { row: newRow } = $table.insertAt(record, -1);
      $table.setActiveCell(newRow, "efficiency");
      this.reRenderTable();
    },
    reRenderTable() {
      const newData = this.tablePage.listPage;
      this.tablePage.listPage = [];
      setTimeout(() => {
        this.tablePage.listPage = newData;
      }, 100);
    },

    /**
     * @desc 删除行数据
     */
    async delRow() {
      const { rows } = await this.$refs.xTable.removeCheckboxRow();
      if (rows && rows.length > 0) {
        const newArr = [];
        const tempar = rows.map(item => item.index);
        this.tableData.forEach(item => {
          if (tempar.indexOf(item.index) == -1) {
            newArr.push(item);
          }
        });
        this.tableData = newArr;
      } else {
        this.$Message.warning("没有可删除的数据！");
      }
    },

    saveData() {
      // 数据验证
      if (!(this.tableData && this.tableData.length > 0)) {
        this.$Message.warning("没有可保存的数据！");
        return;
      }

      // 时间
      const time = this.tableData.map(item => item.time);
      // 车速
      const speed = this.tableData.map(item => item.speed);
      // 载荷
      const load = this.tableData.map(item => item.load);
      // 坡度
      const gradient = this.tableData.map(item => item.gradient);

      const param = {
        time: JSON.stringify(time),
        speed: JSON.stringify(speed),
        load: JSON.stringify(load),
        gradient: JSON.stringify(gradient),
        tableData: JSON.stringify(this.tableData),
        drivingCycleId: this.drivingCycleId
      };
      this.loading = true;
      drivingCycleTbApi
        .addDrivingCycleTb(param)
        .then(res => {
          this.$Message.warning("保存成功");
        })
        .finally(() => {
          this.loading = false;
        });
    },

    /**
     * 初始化列表数据
     */
    initData() {
      this.loading = true;
      drivingCycleTbApi
        .getByDrivingCycleId(this.drivingCycleId)
        .then(res => {
          console.log("---->>>", res);
          const data = res.data;
          if (data) {
            // 组合table数据
            const tableData = JSON.parse(data.tableData);
            if (tableData && tableData.length > 0) {
              this.tableData = tableData;
              this.findList();
            }
            this.renderEchart();
          }
        })
        .finally(() => {
          this.loading = false;
        });
    }
  }
};
</script>
